package com.hongsen.cn.base;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableInt;

import com.hongsen.cn.Utils.AppManager;
import com.hongsen.cn.Utils.LogUtil;
import com.hongsen.cn.Utils.RxBus;
import com.hongsen.cn.Utils.SPUtil;
import com.hongsen.cn.Utils.ToastUtils;
import com.hongsen.cn.Utils.Tools;
import com.hongsen.cn.application.DayAndMonthApplication;
import com.hongsen.cn.bean.Constants;
import com.hongsen.cn.bean.RxValue;
import com.hongsen.cn.dayandmonth.R;
import com.hongsen.cn.dayandmonth.databinding.ActivityBaseBinding;
import com.hongsen.cn.fragment.AddToolFragment;
import com.hongsen.cn.fragment.DynamicFragment;
import com.hongsen.cn.fragment.ForAShortTimeFragment;
import com.hongsen.cn.fragment.GetOutOfLineFragment;
import com.hongsen.cn.im.JWebSocketClient;
import com.hongsen.cn.im.JWebSocketClientService;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

import static com.hongsen.cn.bean.RxBusEventKey.BASE_TITLE_CLICK;
import static com.hongsen.cn.bean.RxBusEventKey.REFRESH_INTENT;

public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements BaseView, View.OnClickListener {

    public ActivityBaseBinding baseBinding;
    private int msgKey1 = 22;
    private TextView tvTime, tvWeek;
    private Unbinder mBind;
    protected P presenter;
    private LinearLayout li_back, ll_layout, li_exit;
    private boolean isNeedNewTittle = false;
    private String mainStatus;
    private int intentTime = 0;

    protected abstract P createPresenter();

    public FrameLayout baseFl;
    public LinearLayout layoutDT, layoutWG, layoutLSCS;
    public TextView tvWG, tvJDXJ, tvDT, tvLSCS;
    public RelativeLayout layoutJDXJ;
    public TextView tvJDXJWJC;
    public GetOutOfLineFragment getOutOfLineFragment;
    public AddToolFragment addToolFragment;
    public DynamicFragment dynamicFragment;
    public ForAShortTimeFragment forAShortTimeFragment;
    private Context mContext;
    //    private JWebSocketClient client;
    //    private JWebSocketClientService.JWebSocketClientBinder binder;
    //    private JWebSocketClientService jWebSClientService;

    public ObservableInt FBI_WG = new ObservableInt();
    public ObservableInt FBI_JD = new ObservableInt();
    public ObservableInt FBI_JD_CC = new ObservableInt();//超出
    public ObservableInt FBI_DT = new ObservableInt();
    public ObservableInt FBI_CS = new ObservableInt();


    @RequiresApi(api = Build.VERSION_CODES.N)
    @SuppressLint({"WrongViewCast", "CheckResult"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        baseBinding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.activity_base, null, false);
        baseBinding.setActivity(this);
        setContentView(baseBinding.getRoot());
        ButterKnife.bind(this);
        baseFl = findViewById(R.id.base_fl);
        layoutDT = findViewById(R.id.layoutDT);
        layoutJDXJ = findViewById(R.id.layoutJDXJ);
        layoutWG = findViewById(R.id.layoutWG);
        layoutLSCS = findViewById(R.id.layoutLSCS);
        tvTime = findViewById(R.id.tvTime);
        tvWeek = findViewById(R.id.tvWeek);

        tvWG = findViewById(R.id.tvWG);
        tvJDXJ = findViewById(R.id.tvJDXJ);
        tvJDXJWJC = findViewById(R.id.tvJDXJWJC);//加戴械具超期的
        tvDT = findViewById(R.id.tvDT);
        tvLSCS = findViewById(R.id.tvLSCS);

        tvWG.setText(String.valueOf(FBI_WG.get()));
        tvJDXJ.setText(String.valueOf(FBI_JD.get()));
        tvJDXJWJC.setText(String.valueOf(FBI_JD_CC.get()));
        tvDT.setText(String.valueOf(FBI_DT.get()));
        tvLSCS.setText(String.valueOf(FBI_CS.get()));

        layoutDT.setOnClickListener(this);
        layoutJDXJ.setOnClickListener(this);
        layoutWG.setOnClickListener(this);
        layoutLSCS.setOnClickListener(this);


        //私有的初始化DataBinding和ViewModel方法
        presenter = createPresenter();
        AppManager.getInstance().addActivity(this);
        if (isNeedNewTitle(isNeedNewTittle)) {
            li_back.setVisibility(View.GONE);
        }
        initView();
        mBind = ButterKnife.bind(this);
        initData();
        initEvent();

        //开启webSocket长连接
        //initService();

        //开启stomp
        //initStomp();

        RxBus.getDefault()
                .toObservable(RxValue.class)
                .observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Consumer<RxValue>() {
                    @Override
                    public void accept(RxValue rxValue) throws Exception {
                        try {
                            if (rxValue.getKey().equals("module_FBI_WG")) {
                                FBI_WG.set(Integer.valueOf(rxValue.getValue()));
                            } else if (rxValue.getKey().equals("module_FBI_JD")) {
                                FBI_JD.set(Integer.valueOf(rxValue.getValue()));
                            } else if (rxValue.getKey().equals("module_FBI_JD_CC")) {
                                FBI_JD_CC.set(Integer.valueOf(rxValue.getValue()));
                            } else if (rxValue.getKey().equals("module_FBI_DT")) {
                                FBI_DT.set(Integer.valueOf(rxValue.getValue()));
                            } else if (rxValue.getKey().equals("module_FBI_CS")) {
                                FBI_CS.set(Integer.valueOf(rxValue.getValue()));
                            }
                        } catch (Exception e) {
                            //LogUtil.e("basetitle返回null");

                        }
                    }
                });


        new TimeThread().start();
    }

    /**
     * 是否需要新的title，如果需要返回true
     *
     * @return
     */
    public boolean isNeedNewTitle(boolean isNeedNewTittle) {
        this.isNeedNewTittle = isNeedNewTittle;
        return isNeedNewTittle;
    }

    public String wg, jd, jd_cc, dt, cs;

    @Override
    protected void onResume() {
        super.onResume();
        wg = SPUtil.getString("module_title_wg", "");
        jd = SPUtil.getString("module_title_jd", "");
        jd_cc = SPUtil.getString("module_title_jd_cc", "");
        dt = SPUtil.getString("module_title_dt", "");
        cs = SPUtil.getString("module_title_cs", "");

        if (!TextUtils.isEmpty(wg)) {
            FBI_WG.set(Integer.valueOf(wg));
            FBI_JD.set(Integer.valueOf(jd));
            if (Integer.valueOf(jd_cc) > 99) {
                tvJDXJWJC.setText("99+");
            } else {
                FBI_JD_CC.set(Integer.valueOf(jd_cc));
            }
            FBI_DT.set(Integer.valueOf(dt));
            FBI_CS.set(Integer.valueOf(cs));
        }
        tvTime.setText(getTime());
        tvWeek.setText(getWeek());

    }

    /**
     * 隐藏退出键
     */
    public void hideExit() {
        this.li_exit.setVisibility(View.GONE);
    }

    /**
     * 设置用户姓名和头像
     */
    private void initUserName() {


    }

    /**
     * 抽象化数据
     */
    protected abstract void initData();

    /**
     * 抽象化布局
     */
    protected abstract void initView();

    @Override
    public void onClick(View v) {
        int sS_ID = v.getId();
        if (sS_ID == R.id.layoutDT) {
            RxBus.getDefault().post(new RxValue(BASE_TITLE_CLICK, "动态人员"));
        } else if (sS_ID == R.id.layoutJDXJ) {
            RxBus.getDefault().post(new RxValue(BASE_TITLE_CLICK, "加戴械具"));
        } else if (sS_ID == R.id.layoutWG) {
            RxBus.getDefault().post(new RxValue(BASE_TITLE_CLICK, "今日违规"));
        } else if (sS_ID == R.id.layoutLSCS) {
            RxBus.getDefault().post(new RxValue(BASE_TITLE_CLICK, "出所人员"));
        }
    }


    /**
     * 事件监听
     */
    private void initEvent() {

    }


    /**
     * @param s
     */
    public void showtoast(String s) {
        Tools.dispToast(s);
    }

    @Override
    public void showLoading() {
        //showLoadingDialog();
    }


    @Override
    public void hideLoading() {
        //closeLoadingDialog();
    }

    @Override
    public void showError(String msg) {
        showtoast(msg);
    }

    @Override
    public void showNoData() {
        Tools.dispToast(getString(R.string.no_data));
    }

    @Override
    public void onErrorCode(BaseModel model) {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.detachView();
        }
        // 必须调用该方法，防止内存泄漏
        if (mBind != null) {
            mBind.unbind();
        }
    }

    public class TimeThread extends Thread {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = msgKey1;
                    mHandler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    /**
     * 显示时间、周期、年月日
     * 显示通知、显示当前工作进度
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 22:
                    tvTime.setText(getTime());
                    tvWeek.setText(getWeek());

                    if (intentTime == 0) {
                        RxBus.getDefault().post(new RxValue(REFRESH_INTENT, "yes"));
                    }
                    if (intentTime > DayAndMonthApplication.returnTime) {
                        intentTime = 0;
                    } else {
                        intentTime++;
                    }

                    break;
                default:
                    break;
            }
        }
    };

    //获得当前年月日时分秒星期
    public String getTime() {
        return new SimpleDateFormat("HH:mm").format(new Date());
    }

    public String getWeek() {
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        String mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
        if ("1".equals(mWay)) {
            mWay = "天";
        } else if ("2".equals(mWay)) {
            mWay = "一";
        } else if ("3".equals(mWay)) {
            mWay = "二";
        } else if ("4".equals(mWay)) {
            mWay = "三";
        } else if ("5".equals(mWay)) {
            mWay = "四";
        } else if ("6".equals(mWay)) {
            mWay = "五";
        } else if ("7".equals(mWay)) {
            mWay = "六";
        }
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " " + "星期" + mWay;
    }

}